from django.shortcuts import render,HttpResponse
import random
from utils.tencent.sms import send_sms_single
from django.conf import settings

# Create your views here.
def send_sms(request):
    # 发送短信
    tpl = request.GET.get('tpl')
    tpl_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    if not tpl_id:
        return HttpResponse('模板不存在')
    code = random.randrange(1000,9999)
    res = send_sms_single('15771388512', tpl_id, [code,])
    if res['result'] == 0:
        return HttpResponse('发送成功')
    else:
        return HttpResponse(res['errmsg'])

from django import forms
from app01 import models
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError

class RegisterModelForm(forms.ModelForm):
    mobile_phone = forms.CharField(label='手机号码',validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$','手机号码格式错误',)])
    password = forms.CharField(label='密码',widget=forms.PasswordInput())
    confirm_password = forms.CharField(label='确认密码',widget=forms.PasswordInput())
    code = forms.CharField(label='验证码',)
    class Meta:
        model = models.UserInfo
        fields = ['username','email','password','confirm_password','mobile_phone','code']
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = f'请输入{field.label}'

def register(request):
    form = RegisterModelForm()
    if request.method == "POST":
        form_obj = forms.RegisterModelForm(request.POST)
        if form_obj.is_valid():
            pass
            # form_obj.save()
            # return redirect()
    context = {
        "form_obj": form_obj,
    }
    return render(request,'app01/register.html',{'form':form})

